from rest_framework import viewsets, status
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from django.db.models import Q, Count
from django.utils import timezone
from datetime import timedelta
from .models import Category, Tag, Link, UserVisit, UserPreference, Favorite
from .serializers import (
    CategorySerializer, TagSerializer, LinkSerializer,
    UserVisitSerializer, UserPreferenceSerializer,
    LinkTagsUpdateSerializer, LinkTagsUpdateResponseSerializer,
    VisitStatsQuerySerializer, VisitStatsResponseSerializer,
    LinkVisitRequestSerializer, LinkVisitResponseSerializer,
    LinkRecommendationResponseSerializer,
    FavoriteSerializer, FavoriteCreateSerializer, FavoriteResponseSerializer
)
from .filters import (
    CategoryFilter, TagFilter, LinkFilter,
    UserVisitFilter, UserPreferenceFilter
)
from drf_spectacular.utils import extend_schema
from accounts.decorators import register_action_permission
from django.db.models.functions import ExtractHour, ExtractWeekDay

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = CategoryFilter
    search_fields = ['name', 'description']
    ordering_fields = ['order', 'name', 'created_at']

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user, updated_by=self.request.user)

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user)

class TagViewSet(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = TagFilter
    search_fields = ['name', 'description']
    ordering_fields = ['name', 'created_at']

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user, updated_by=self.request.user)

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user)

class LinkViewSet(viewsets.ModelViewSet):
    queryset = Link.objects.all()
    serializer_class = LinkSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = LinkFilter
    search_fields = ['title', 'description', 'url']
    ordering_fields = ['visit_count', 'created_at', 'title']

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user, updated_by=self.request.user)

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user)


    @extend_schema(
        request=LinkTagsUpdateSerializer,
        responses={200: LinkTagsUpdateResponseSerializer},
        description='更新链接标签'
    )
    @register_action_permission("Can update link tags")
    @action(detail=True, methods=['post'])
    def update_tags(self, request, pk=None):
        """更新链接标签"""
        link = self.get_object()
        serializer = LinkTagsUpdateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 更新标签
        link.tags.set(serializer.validated_data['tag_ids'])
        link.save()
        
        # 构建响应数据
        response_data = {
            'success': True,
            'message': '标签已更新',
            'link': link
        }
        
        response_serializer = LinkTagsUpdateResponseSerializer(response_data)
        return Response(response_serializer.data)

    @extend_schema(
        # request=LinkVisitRequestSerializer,
        request=None,
        responses={200: LinkVisitResponseSerializer},
        description='记录链接访问'
    )
    @register_action_permission("Can record link visit")
    @action(detail=True, methods=['post'])
    def visit(self, request, *args, **kwargs):
        """记录链接访问"""
        link = self.get_object()
        link.visit_count += 1
        link.save()
        
        UserVisit.objects.create(
            user=request.user,
            link=link,
            created_by=request.user,
            updated_by=request.user
        )
        
        response_serializer = LinkVisitResponseSerializer({
            'success': True,
            'message': '访问记录已创建'
        })
        return Response(response_serializer.data)

    @extend_schema(
        responses={200: LinkRecommendationResponseSerializer},
        description='获取推荐链接'
    )
    @register_action_permission("Can get recommended links")
    @action(detail=False, methods=['get'])
    def recommended(self, request):
        """获取推荐链接"""
        user_visits = UserVisit.objects.filter(user=request.user)
        visited_links = Link.objects.filter(user_visits__in=user_visits)
        
        # 获取用户偏好
        try:
            preference = UserPreference.objects.get(user=request.user)
            favorite_categories = preference.favorite_categories.all()
            favorite_tags = preference.favorite_tags.all()
        except UserPreference.DoesNotExist:
            favorite_categories = []
            favorite_tags = []
        
        # 基于用户历史访问和偏好推荐链接
        recommended_links = Link.objects.filter(
            Q(category__in=favorite_categories) |
            Q(tags__in=favorite_tags) |
            Q(category__in=visited_links.values('category')) |
            Q(tags__in=visited_links.values('tags'))
        ).exclude(
            id__in=visited_links.values('id')
        ).distinct().order_by('-visit_count')[:10]
        
        # 构建响应数据
        response_data = {
            'links': recommended_links,
            'recommendation_reason': '基于您的访问历史和偏好推荐'
        }
        
        response_serializer = LinkRecommendationResponseSerializer(response_data)
        return Response(response_serializer.data)

    @extend_schema(
        request=None,
        description="收藏或取消收藏指定的链接",
        responses={200: FavoriteResponseSerializer},
   
    )
    @register_action_permission('Can favorite link')
    @action(detail=True, methods=['POST'], permission_classes=[IsAuthenticated])
    def favorite(self, request, pk=None):
        link = self.get_object()
        
        favorite, created = Favorite.objects.get_or_create(
            user=request.user,
            link=link
        )
        
        if not created:
            # If already favorited, remove it (toggle behavior)
            favorite.delete()
            return Response({
                'success': True,
                'message': '已取消收藏',
            })
        
        serializer = FavoriteSerializer(favorite)
        return Response({
            'success': True,
            'message': '收藏成功',
            'favorite': serializer.data
        })

class UserVisitViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = UserVisit.objects.all()
    serializer_class = UserVisitSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = UserVisitFilter
    ordering_fields = ['created_at']

    def get_queryset(self):
        if self.request.user.is_staff:
            return UserVisit.objects.all()
        return UserVisit.objects.filter(user=self.request.user)

class UserPreferenceViewSet(viewsets.ModelViewSet):
    queryset = UserPreference.objects.all()
    serializer_class = UserPreferenceSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_class = UserPreferenceFilter

    def get_queryset(self):
        if self.request.user.is_staff:
            return UserPreference.objects.all()
        return UserPreference.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(
            user=self.request.user,
            created_by=self.request.user,
            updated_by=self.request.user
        )

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user)

class FavoriteViewSet(viewsets.ModelViewSet):
    serializer_class = FavoriteSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return Favorite.objects.filter(user=self.request.user).select_related('link', 'user')
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    
    @extend_schema(
        summary="获取我的收藏",
        description="获取当前用户的所有收藏链接",
        responses={200: FavoriteSerializer(many=True)},
        tags=["收藏"]
    )
    @register_action_permission
    @action(detail=False, methods=['GET'])
    def my_favorites(self, request):
        favorites = self.get_queryset()
        serializer = self.get_serializer(favorites, many=True)
        return Response(serializer.data)

class VisitStatsViewSet(viewsets.ViewSet):
    """访问统计视图集"""
    permission_classes = [IsAuthenticated]

    @extend_schema(
        parameters=[VisitStatsQuerySerializer],
        responses={200: VisitStatsResponseSerializer}
    )
    def list(self, request):
        # 验证查询参数
        query_serializer = VisitStatsQuerySerializer(data=request.query_params)
        query_serializer.is_valid(raise_exception=True)
        days = query_serializer.validated_data['days']

        # 获取时间范围
        end_date = timezone.now()
        start_date = end_date - timedelta(days=days)

        # 获取用户的访问记录
        visits = UserVisit.objects.filter(
            user=request.user,
            created_at__range=(start_date, end_date)
        )

        # 按日期分组统计访问次数
        daily_stats = visits.values('created_at__date').annotate(
            visit_count=Count('id')
        ).order_by('created_at__date')

        # 获取最常访问的链接
        popular_links = visits.values(
            'link'
        ).annotate(
            visit_count=Count('id')
        ).order_by('-visit_count')[:5]

        # 获取链接详情
        popular_links_data = []
        for item in popular_links:
            link = Link.objects.get(id=item['link'])
            popular_links_data.append({
                'id': link.id,
                'title': link.title,
                'url': link.url,
                'visit_count': item['visit_count']
            })

        # 按分类统计访问次数
        category_stats = visits.values(
            'link__category'
        ).annotate(
            visit_count=Count('id')
        ).order_by('-visit_count')

        # 获取分类详情
        category_stats_data = []
        for item in category_stats:
            if item['link__category']:
                category = Category.objects.get(id=item['link__category'])
                category_stats_data.append({
                    'id': category.id,
                    'name': category.name,
                    'visit_count': item['visit_count']
                })

        # 按小时统计访问次数
        hourly_stats = visits.annotate(
            hour=ExtractHour('created_at')
        ).values('hour').annotate(
            visit_count=Count('id')
        ).order_by('hour')

        # 按星期统计访问次数
        weekday_stats = visits.annotate(
            weekday=ExtractWeekDay('created_at')
        ).values('weekday').annotate(
            visit_count=Count('id')
        ).order_by('weekday')

        # 按标签统计访问次数
        tag_stats = visits.values(
            'link__tags'
        ).annotate(
            visit_count=Count('id')
        ).order_by('-visit_count')

        # 获取标签详情
        tag_stats_data = []
        for item in tag_stats:
            if item['link__tags']:
                tag = Tag.objects.get(id=item['link__tags'])
                tag_stats_data.append({
                    'id': tag.id,
                    'name': tag.name,
                    'visit_count': item['visit_count']
                })

        # 构造响应数据
        response_data = {
            'daily_stats': list(daily_stats),
            'hourly_stats': list(hourly_stats),
            'weekday_stats': list(weekday_stats),
            'popular_links': popular_links_data,
            'category_stats': category_stats_data,
            'tag_stats': tag_stats_data,
            'total_visits': visits.count()
        }

        # 序列化响应数据
        response_serializer = VisitStatsResponseSerializer(data=response_data)
        response_serializer.is_valid(raise_exception=True)
        
        return Response([response_serializer.validated_data])
